import { getUserProfile, updatePhoto, updateUserProfile } from '@/store/actions/profile'
import { useInitialState } from '@/utils/hooks'
import { Button, List, DatePicker, NavBar, Popup, Toast, Dialog } from 'antd-mobile'
import classNames from 'classnames'
import { useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
import EditInput from './components/EditInput'
import EditList from './components/EditList'
import dayjs from 'dayjs'

import styles from './index.module.scss'
import { logout } from '@/store/actions/login'
import { useHistory } from 'react-router-dom'

const Item = List.Item

const ProfileEdit = () => {

  const historty = useHistory();
  const { userProfile } = useInitialState(getUserProfile, 'profile')
  const [showInput, setShowInput] = useState<{
    type: '' | 'name' | 'intro'
    visible: boolean
  }>({
    type: '',
    visible: false
  })

  const [showList, setShowList] = useState<{
    type: '' | 'photo' | 'gender'
    visible: boolean
  }>({
    type: '',
    visible: false
  })

  const [showBirthday, setShowBirthday] = useState(false)

  const dispatch = useDispatch();

  const hideInput = () => {
    setShowInput({
      visible: false,
      type: ''
    });
  }

  const hideList = () => {
    setShowList({
      visible: false,
      type: ''
    })
  }

  const onShowBirthday = () => {
    setShowBirthday(true)
  }

  const onHideBirthday = () => {
    setShowBirthday(false)
  }

  const fileRef = useRef<HTMLInputElement>(null);

  const onUpdate = async (key: string, value: string) => {
    if (key === 'photo') {
      fileRef.current?.click()
      return
    }
    
    await dispatch(updateUserProfile({
      [key]: value
    }))

    Toast.show({
      content: '修改成功',
      icon: 'success'
    });

    hideInput()
    hideList()
  }

  const changePhoto = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files![0];
    const formData = new FormData();
    formData.append('photo', file)
    await dispatch(updatePhoto(formData))
    Toast.show({
      content: '修改头像成功',
      icon: 'success'
    })
    hideList();
  }

  const logoutFn = () => {
    Dialog.confirm({
      title: "温馨提示",
      content: '你确定要退出吗？',
      onConfirm: () => {
        //点击了确定按钮
        // 1. 清除Token
        dispatch(logout())
        // 2.跳转到登录页面
        historty.push('/login');
      }
    })
  }

  return (
    <div className={styles.root}>
      <div className="content">
        {/* 标题 */}
        <NavBar
          style={{
            '--border-bottom': '1px solid #F0F0F0'
          }}
          onBack={() => {
            historty.go(-1);
          }}
        >
          个人信息
        </NavBar>

        <div className="wrapper">
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <Item
              extra={
                <span className="avatar-wrapper">
                  <img
                    width={24}
                    height={24}
                    src={userProfile.photo}
                    alt=""
                  />
                </span>
              }
              arrow
              onClick={() => {
                setShowList({
                  type: 'photo',
                  visible: true
                })
              }}
            >
              头像
            </Item>
            <Item
              arrow
              extra={userProfile.name}
              onClick={() => {
                setShowInput({
                  visible: true,
                  type: 'name'
                })
              }}
            >
              昵称
            </Item>
            <Item
              arrow
              extra={
                <span className={classNames('intro', 'normal')}>
                  {userProfile.intro || '未填写'}
                </span>
              }
              onClick={() => {
                setShowInput({
                  type: 'intro',
                  visible: true
                })
              }}
            >
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item
              arrow
              extra={userProfile.gender === 0 ? '男' : '女'}
              onClick={() => {
                setShowList({
                  visible: true,
                  type: 'gender'
                })
              }}
            >
              性别
            </Item>
            <Item arrow extra={userProfile.birthday} onClick={onShowBirthday}>
              生日
            </Item>
          </List>

          <DatePicker
            visible={showBirthday}
            value={new Date(userProfile.birthday)}
            title="选择年月日"
            min={new Date('1900-01-01')}
            max={new Date()}
            onClose={onHideBirthday}
            onConfirm={(value) => {
              onUpdate('birthday', dayjs(value).format('YYYY-MM-DD'))
            }}
          />
        </div>

        <div className="logout">
          <Button className="btn" onClick={logoutFn}>退出登录</Button>
        </div>
      </div>
      <Popup
        visible={showInput.visible}
        position="right"
        bodyStyle={{ width: '100vw' }}
        destroyOnClose={true}
      >
        <EditInput
          type={showInput.type}
          hideInput={hideInput}
          onUpdate={onUpdate}
        ></EditInput>
      </Popup>
      <Popup
        visible={showList.visible}
        position="bottom"
        destroyOnClose
      >
        <EditList
          type={showList.type}
          hideList={hideList}
          onUpdate={onUpdate}
        ></EditList>
      </Popup>
      <input
        ref={fileRef}
        type="file"
        hidden
        onChange={changePhoto}
      />
    </div>
  )
}

export default ProfileEdit
